//
//  KKHomeButton.m
//  PhnixHome
//
//  Created by Levy Xu on 2018/4/7.
//  Copyright © 2018年 Levy Xu. All rights reserved.
//

#import "KKHomeButton.h"

@implementation KKHomeButton

- (void)dealloc
{
    [NNCDC removeObserver:self];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.backgroundColor = UIColorWhite;
        self.titleLabel.font = CodeFontMake(16);
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.qmui_automaticallyAdjustTouchHighlightedInScrollView = YES;
        
        self.modeLabel = [[QMUILabel alloc] initWithFrame:CGRectZero];
        self.modeLabel.font = CodeFontMake(14);
        self.modeLabel.textAlignment = NSTextAlignmentCenter;
        self.modeLabel.textColor = UIColorGray5;
        [self addSubview:self.modeLabel];
        
        [self setTitleColor:UIColorGray2 forState:UIControlStateNormal];
        [self showCornerRadius];
        [self showShadow];
    }
    return self;
}

-(void)setModel:(id)model {
    _model = model;
    
    [self displayModel];
    
    [NNCDC removeObserver:self name:kDeviceStatusChangedNotification object:nil];
    [NNCDC addObserver:self selector:@selector(statusChanged:) name:kDeviceStatusChangedNotification object:nil];
}

-(void)displayModel {
    if (!_model) {
        return;
    }
    [self setImage:[_model displayImage] forState:UIControlStateNormal];
    NSString *displayName = [_model displayName];
    NSArray *array = [displayName componentsSeparatedByString:@"\n"];
    if (array.count > 0) {
        [self setTitle:array[0] forState:UIControlStateNormal];
        if (array.count == 2) {
            self.modeLabel.text = array[1];
        } else {
            self.modeLabel.hidden = YES;
        }
    }
    
    [self setNeedsLayout];
}

-(void)statusChanged:(NSNotification *)notification {
    id model = notification.object;
    if (model == _model) {
        [self displayModel];
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    if (CGRectIsEmpty(self.bounds)) {
        return;
    }
    
    float width = floorf(MIN(self.qmui_width, self.qmui_height) / 2);
    float modeHeight = self.modeLabel.isHidden ? 0 : 25;
    CGFloat start = (self.qmui_height - width - 25 - modeHeight) / 2;
    self.imageView.frame = CGRectMake(self.qmui_width / 2 - width / 2, start, width, width);
    self.titleLabel.frame = CGRectMake(5, self.imageView.qmui_bottom + 7, self.qmui_width - 10, 20);
    
    if (!self.modeLabel.isHidden) {
        self.modeLabel.frame = CGRectMake(5, self.titleLabel.qmui_bottom + 3, self.qmui_width - 10, 20);
    }
}

@end
